'use strict';

exports.index = async ctx => {
  const { query } = ctx.request;
  let pageSize = 10;
  if (query.pageSize) pageSize = Number(query.pageSize);
  const where = {};
  const loginService = ctx.app.weapp.LoginService.create(ctx.request, ctx.response);
  const checkedData = await loginService.check();
  const { openId } = checkedData.userInfo;
  console.log('participated openId', openId);
  const { userId } = await ctx.model.WechatAccount.findById(openId);
  const { status, id, userStatus } = query;
  if (userId) where.userId = userId;
  if (status) where.status = status;
  if (userStatus) where.userStatus = userStatus;
  if (id) where.id = id;
  const options = {
    limit: pageSize,
    offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
    order: [
      [ 'id', 'DESC' ],
    ],
    where,
  };
  const {
    count: total, rows: list,
  } = await ctx.model.Order.findAndCountAll(options);
  console.log('controller orders index list', list);
  ctx.body = {
    list,
    pagination: {
      total,
      pageSize,
      current: parseInt(query.currentPage, 10) || 1,
    },
  };
};

exports.create = async ctx => {
  ctx.validate({
    itemId: { type: 'int' },
    couponId: { type: 'int', required: false },
    type: { type: 'string' },
    remark: { type: 'string', required: false },
  });
  const { itemId, couponId, type, remark } = ctx.request.body;
  console.log('orders create items', itemId);
  console.log('orders create couponId', couponId);
  console.log('orders create type', type);
  const item = await ctx.model.Item.findByPk(itemId);// 找到商品类型
  const loginService = ctx.app.weapp.LoginService.create(ctx.request, ctx.response);
  const checkedData = await loginService.check();
  const { openId } = checkedData.userInfo;
  const { userId } = await ctx.model.WechatAccount.findByPk(openId);
  const { receiverAddress, receiverName, receiverPhone } = await ctx.model.User.findByPk(userId);
  console.log('orders create userId', userId);
  switch (item.itemType) {
    case 'present': {
      console.log('item.itemType  present');
      const { price } = item;
      console.log('item.itemType  present orders create price', price);
      const data = {
        title: `${item.title}`,
        price,
        userId,
        amount: price,
        payment: 'wechatPay',
        imageHash: item.imageHash,
        remark,
        receiverAddress,
        receiverName,
        receiverPhone,
      };
      console.log('item.itemType  present orders create data', data);
      const order = await ctx.model.Order.create(data);
      console.log('item.itemType  present orders create order', order);
      const orderItemData = {
        title: `${item.title}`,
        imageHash: item.imageHash,
        price,
        userId,
        itemId,
        orderId: order.id,
        number: 1,
        amount: price,
      };
      await ctx.model.OrderItem.create(orderItemData);
      const { id: tradeId } = await order.createTrade({ price: data.amount });
      console.log('orders create tradeId', tradeId);
      const out_trade_no = String(tradeId);
      ctx.body = await ctx.app.wechatPay.requestPayment({
        body: order.title,
        out_trade_no,
        total_fee: data.amount,
        spbill_create_ip: ctx.get('X-Real-IP'),
        trade_type: 'JSAPI',
        openid: checkedData.userInfo.openId,
      });
    }
      break;
    case 'commodities': {
      const store = await ctx.model.Store.findByPk(item.storeId);
      const { price } = item;
      const coupon = await ctx.model.Coupon.findByPk(couponId);
      const data = {
        title: `${item.title}`,
        price,
        storeId: item.storeId,
        userId,
        amount: price,
        phone: store.phone,
        address: store.address,
        imageHash: item.imageHash,
        receiverAddress,
        receiverName,
        receiverPhone,
        remark,
      };
      console.log('orders create data', data);
      if (coupon && price >= coupon.require) {
        console.log('coupon && price >= coupon.require');
        data.couponId = coupon.id;
        data.discount = coupon.amount;
        data.amount -= coupon.amount;
      }
      if (type === 'balance') {
        data.payment = 'balance';
        console.log('data.payment =data.payment =data.payment =', data);
        const order = await ctx.model.Order.create(data);
        const currentUser = await ctx.model.User.findByPk(userId);
        console.log('currentUser.balance currentUser.balance', currentUser.balance);
        if (currentUser.balance && currentUser.balance > price) {
          const userBalance = currentUser.balance;
          const newbalance = userBalance - Number(data.amount);
          console.log('type balance currentUser newbalance', newbalance);
          const recordData = {
            userId: currentUser.id,
            balance: newbalance,
            price,
            add: false,
            remark: '余额购买消耗',
          };
          // 创建余额记录
          await ctx.model.BalanceRecord.create(recordData);
          const storeClass = await this.ctx.model.StoreClass.findByPk(store.storeClassId);
          const newOveRall = Number(store.oveRall) + price;
          const newStoreClassOveRall = Number(storeClass.oveRall) + price;
          // 更新店铺类型销售额
          await storeClass.update({ oveRall: newStoreClassOveRall });
          // 更新店铺销售额
          await store.update({ oveRall: newOveRall });
          // 商家订单通知
          const sendData = {
            phone: store.phone,
            TemplateCode: 'SMS_158547442',
          };
          await ctx.service.smsCode.send(sendData);
          const { storeType } = await ctx.model.Store.findByPk(item.storeId);
          if (storeType === 'store') {
            await order.update({
              status: 'completed',
              userStatus: 'completed',
            });
          } else {
            await order.update({
              status: 'completed',
            });
          }
          await currentUser.update({ balance: newbalance });
          const orderItemData = {
            title: `${item.title}`,
            imageHash: item.imageHash,
            price,
            storeId: item.storeId,
            userId,
            itemId,
            orderId: order.id,
            number: 1,
            amount: price,
          };
          await ctx.model.OrderItem.create(orderItemData);
          if (coupon && price >= coupon.require) await coupon.update({ orderId: order.id });
          ctx.body = order;
        }
      } else if (type === 'weapp') {
        data.payment = 'wechatPay';
        const order = await ctx.model.Order.create(data);
        const orderItemData = {
          title: `${item.title}`,
          imageHash: item.imageHash,
          price,
          storeId: item.storeId,
          userId,
          itemId,
          orderId: order.id,
          number: 1,
          amount: price,
        };
        await ctx.model.OrderItem.create(orderItemData);
        if (coupon && price >= coupon.require) await coupon.update({ orderId: order.id });
        console.log('orders create order', order);
        const { id: tradeId } = await order.createTrade({ price: data.amount, storeId: item.storeId });
        console.log('orders create tradeId', tradeId);
        const out_trade_no = String(tradeId);
        console.log('orders create ut_trade_no');
        ctx.body = await ctx.app.wechatPay.requestPayment({
          body: order.title,
          out_trade_no,
          total_fee: data.amount,
          spbill_create_ip: ctx.get('X-Real-IP'),
          trade_type: 'JSAPI',
          openid: checkedData.userInfo.openId,
        });
      }
    }
      break;
    default:

  }
};

exports.show = async ctx => {
  let pageSize = 10;
  const { query } = ctx.request;
  if (query.pageSize) pageSize = Number(query.pageSize);
  console.log('controller orders ctx.params.id', ctx.params.id);
  const order = await ctx.model.Order.findByPk(ctx.params.id);
  console.log('controller orders show order', order);
  if (order) {
    const orderId = order.id;
    console.log('controller orders orderId', orderId);
    const options = {
      limit: pageSize,
      offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
      where: { orderId },
    };
    console.log('controller orders options', options);
    const orderItems = await ctx.model.OrderItem.findAll(options);
    console.log('controller orders show orderItems', orderItems);
    const data = { order, itemId: orderItems.itemId };
    ctx.body = data;
  } else {
    ctx.status = 404;
  }
};
